//
//  M4SuggestionViewController.swift
//  M4
//
//  Created by YuChuang on 2024/8/9.
//

import UIKit
import AVFoundation
import Photos

protocol M4SuggestPhotoActionProtocol : NSObject {
    func addPhoto()
}

class M4SuggestionViewController: M4BaseViewController, UITextViewDelegate {
    
    @IBOutlet weak var M4SuggestionTitleLable3: UILabel!
    @IBOutlet weak var M4SuggestionTitleLabel2: UILabel!
    @IBOutlet weak var M4SuggestionTitleLable1: UILabel!
    @IBOutlet weak var M4SuggestionView: UIView!
    
    @IBOutlet weak var M4SuggestionTextView: M4TextView!
    
    @IBOutlet weak var M4SuggestionCountLabel: UILabel!
    
    @IBOutlet weak var M4SuggestPhotoView: UIView!
    
//    @IBOutlet weak var M4SuggestPhotoLabel: UILabel!
    
    @IBOutlet weak var M4SuggSubmitButton: UIButton!
    
    @IBOutlet weak var M4SuggentionPhoneTextView: M4TextView!
    weak var delegate: M4SuggestPhotoActionProtocol?
    
    private var photoUrls: [String] = ["opinion_icon_photo"]
    
    let M4SuggestionTextMax = 1000

    override func viewDidLoad() {
        super.viewDidLoad()

        M4NavBarColor = .white
        M4BackIcon = "icon_back_black"
        M4NavTitle(M4Title: "Comentarios", M4NavTitleColor: COLOR_333333)
        M4SuggestionTextView.placeHolder = "Por favor, describa aquí el problema que encontró, relacionado con la calidad del servicio, si necesita complementar las credenciales haga clic en el «+» de abajo, suba sus capturas de pantalla"
        M4SuggestionTextView.delegate = self
        delegate = self
        
        M4SuggestionTextView.layer.borderColor = COLOR_CCCCCC.cgColor
        M4SuggestionTextView.layer.borderWidth = 0.5
        M4SuggestionView.layer.cornerRadius = 2
        
        M4SuggentionPhoneTextView.delegate = self
        M4SuggentionPhoneTextView.layer.borderColor = COLOR_CCCCCC.cgColor
        M4SuggentionPhoneTextView.layer.borderWidth = 0.5
        M4SuggentionPhoneTextView.layer.cornerRadius = 2
        M4SuggentionPhoneTextView.placeHolder = "Por favor, ingrese WhatsApp/teléfono/correo"
        
        
        setTitleLable1()
        setTitleLabel2()
        setTitleLabel3()
        
        creatPhotoView()
    }
    
    private func setTitleLable1() {
        let str1 = "*"
        let str2 = "Reclamos y comentarios "
        let str3 = "(obligatorio) "
        let str = str1 + str2 + str3
        let range1 = (str as NSString).range(of: str1)
        let range2 = (str as NSString).range(of: str3)
        
        var attStr = NSMutableAttributedString(string: str)
        attStr.addAttributes([
            .font : UIFont.systemFont(ofSize: 14, weight: .bold),
            .foregroundColor : COLOR_333333
        ], range: NSMakeRange(0, str.count))
        attStr.addAttributes([
            .font : UIFont.systemFont(ofSize: 14, weight: .regular),
            .foregroundColor : COLOR_9D0000
        ], range: range1)
        attStr.addAttributes([
            .font : UIFont.systemFont(ofSize: 14, weight: .regular),
            .foregroundColor : COLOR_999999
        ], range: range2)

        M4SuggestionTitleLable1.attributedText = attStr
    }
    
    private func setTitleLabel3() {
        let str1 = "*"
        let str2 = "Información de contacto "
        let str3 = "(obligatorio) "
        let str = str1 + str2 + str3
        let range1 = (str as NSString).range(of: str1)
        let range2 = (str as NSString).range(of: str3)
        
        var attStr = NSMutableAttributedString(string: str)
        attStr.addAttributes([
            .font : UIFont.systemFont(ofSize: 14, weight: .bold),
            .foregroundColor : COLOR_333333
        ], range: NSMakeRange(0, str.count))
        attStr.addAttributes([
            .font : UIFont.systemFont(ofSize: 14, weight: .regular),
            .foregroundColor : COLOR_9D0000
        ], range: range1)
        attStr.addAttributes([
            .font : UIFont.systemFont(ofSize: 14, weight: .regular),
            .foregroundColor : COLOR_999999
        ], range: range2)

        M4SuggestionTitleLable3.attributedText = attStr
    }
    
    private func setTitleLabel2() {
        let str1 = "Capturas de pantalla de los comentarios "
        let str2 = "\(photoUrls.count - 1)/5"
        let str3 = "\n(mejor si las subes, así será más fácil encontrar el problema)"
        let str = str1 + str2 + str3
        let range2 = (str as NSString).range(of: str2)
        let range3 = (str as NSString).range(of: str3)
        
        var attStr = NSMutableAttributedString(string: str)
        attStr.addAttributes([
            .font : UIFont.systemFont(ofSize: 14, weight: .bold),
            .foregroundColor : COLOR_333333
        ], range: NSMakeRange(0, str.count))
        attStr.addAttributes([
            .font : UIFont.systemFont(ofSize: 14, weight: .regular),
            .foregroundColor : COLOR_333333
        ], range: range2)
        attStr.addAttributes([
            .font : UIFont.systemFont(ofSize: 14, weight: .regular),
            .foregroundColor : COLOR_999999
        ], range: range3)

        M4SuggestionTitleLabel2.attributedText = attStr
    }
    
    private func creatPhotoView() {
//        M4SuggestPhotoLabel.text = "aptura de pantalla del problema" + " \(photoUrls.count - 1)/5"
        for m4view in M4SuggestPhotoView.subviews {
            if m4view is UIButton {
                m4view.removeFromSuperview()
            }
        }
        let edgX = 15.0
        let btnWidth = (M4ScreenWidth - 20 - edgX * 4) / 3.0
        for i in 0...photoUrls.count-1 {
            let button = UIButton()
            button.imageView?.contentMode = .scaleAspectFill
            M4SuggestPhotoView.addSubview(button)
            button.layer.cornerRadius = 2
            button.layer.masksToBounds = true
            button.snp.makeConstraints { make in
                make.left.equalToSuperview().offset((btnWidth + edgX) * Double((i%3)))
                make.top.equalTo(M4SuggestPhotoView.snp.top).offset((btnWidth + edgX) * Double(i/3))
                make.width.height.equalTo(btnWidth)
                if i == photoUrls.count - 1 {
                    make.bottom.equalToSuperview().priority(.high)
                }
            }
            let str = photoUrls[i]
            if str.contains("http") == false {
                button.backgroundColor = .white
                button.setBackgroundImage(UIImage.init(named: str), for: .normal)
            } else {
                button.backgroundColor = UIColor.groupTableViewBackground
                if let url = URL(string: str) {
                    button.sd_setImage(with: url, for: .normal)
                }
                
                let deleteButton = UIButton(type: .custom)
                deleteButton.backgroundColor = .white
                if #available(iOS 13.0, *) {
                    let deleteImage = UIImage(systemName: "xmark.app.fill")
                    deleteImage?.withTintColor(COLOR_00479D)
                    deleteButton.setImage(deleteImage, for: .normal)
                }
                deleteButton.tag = i
                button.addSubview(deleteButton)
                deleteButton.snp.makeConstraints { make in
                    make.top.trailing.equalTo(button)
                    make.width.height.equalTo(24)
                }
                deleteButton.addTarget(self, action: #selector(deleteImage(_:)), for: .touchUpInside)
            }
            
            button.tag = i
            if i == 0 {
                button.addTarget(self, action: #selector(M4SuggestPhotoAction(_:)), for: .touchUpInside)
            }
        }
    }
    
    @objc private func deleteImage(_ button: UIButton) {
        photoUrls.remove(at: button.tag)
        creatPhotoView()
        setTitleLabel2()
    }
    
    private func insertPhotoUrl(_ photoUrl: String) {
        if photoUrls.count >= 2 {
            photoUrls.insert(photoUrl, at: 1)
        } else {
            photoUrls.append(photoUrl)
        }
        if photoUrls.count >= 7 {
            photoUrls.remove(at: 6)
        }
        creatPhotoView()
        setTitleLabel2()
    }
    
    @objc private func M4SuggestPhotoAction(_ sender: UIButton) {
        view.endEditing(true)
        if photoUrls.count > 5 {
            self.view.makeToast("La cantidad excede el límite", position: .center)
            return
        }
        delegate?.addPhoto()
        sender.M4EventUnavailable = false
    }
    
    
    @IBAction func M4SubmitSuggest(_ sender: UIButton) {
        view.endEditing(true)
        M4SubmitSuggestNet()
    }
    
    private func M4UploadPhotoNet(imgBase64: String) {
        let loading = M4LoadingAlertView()
        loading.M4LoadingAlertShow()
        M4PublicNetwork.M4UploadFielNet(imgBase64Str: imgBase64) { success, urlstring in
            loading.M4AlertViewHidden()
            if success {
                self.insertPhotoUrl(urlstring)
            }
        }
    }
    
    private func M4SubmitSuggestNet() {
        if M4SuggestionTextView.text.count == 0 ||
            M4SuggentionPhoneTextView.text.count == 0 {
            self.view.makeToast("Los campos obligatorios no pueden estar en blanco", position: .center)
            M4SuggSubmitButton.M4EventUnavailable = false
            return
        }
        photoUrls.removeFirst()
        var photoUrlString = ""
        for item in photoUrls {
            photoUrlString = photoUrlString + ",\(item)"
        }
//        let para: [String : Any] = ["Oxnh": "ESP", "WYFYUSt": M4UserDataManager.m4UserShare.M4Itemcode, "DFCQ": M4UserDataManager.m4UserShare.M4Token, "VbEU": "52" + M4UserDataManager.m4UserShare.M4UserMobile, "UYW": M4SuggestionTextView.text ?? "", "YLevToYieM": 5, "COBVDdx": photoUrlString.dropFirst(), "mksms": M4SuggentionPhoneTextView.text ?? ""]
        let para: [String : Any] = ["adfew": "ESP", "gasdqw": M4UserDataManager.m4UserShare.M4Itemcode, "fqwq": M4UserDataManager.m4UserShare.M4Token, "ASDWR": "52" + M4UserDataManager.m4UserShare.M4UserMobile, "Gqwrq": M4SuggestionTextView.text ?? "", "dgwer": photoUrlString.dropFirst(), "asdfwe": M4SuggentionPhoneTextView.text ?? ""]
        M4NetworkManager().M4Request(M4NetworkTarget.M4_targetType(.m4comentarios, .post, params: para)) { model in
            self.M4SuggSubmitButton.M4EventUnavailable = false
            if model.code == 1 {
                self.view.makeToast("Enviado con éxito", position: .center)
                DispatchQueue.main.asyncAfter(deadline: .now()+1.0) {
                    self.view.hideToast()
                    self.navigationController?.popViewController(animated: true)
                }
            }
            else {
                self.view.makeToast(model.message, position: .center)
            }
        }
    }
    
    func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool {
        if textView.text.count == 0 && text == " " { return false }
        if text.containsEmoji == true { return false }
        return true
    }
    
    func textViewDidChange(_ textView: UITextView) {
        var textString = textView.text ?? ""
        if textString.count > M4SuggestionTextMax {
            textString = (textString as NSString).substring(to: M4SuggestionTextMax)
        }
        textView.text = textString
        if textView == M4SuggestionTextView {
            M4SuggestionCountLabel.text = "\(textString.count)/\(String(M4SuggestionTextMax))"
        }
    }

}

extension M4SuggestionViewController: M4SuggestPhotoActionProtocol, UIImagePickerControllerDelegate & UINavigationControllerDelegate {
    
    func addPhoto() {
        let alert = UINib(nibName: "M4TakePhotoAlertView", bundle: nil).instantiate(withOwner: self).last as! M4TakePhotoAlertView
        alert.M4TakePhotoCamareBlock = {
            self.M4ShowCamera()
        }
        alert.M4TakePhotoAlbumBlock = {
            self.M4ShowSystemAlbum()
        }
        alert.M4PopViewShow(subview: alert.M4TakePhotoBGView)
    }
    
    private func M4ShowCamera() {
        AVCaptureDevice.requestAccess(for: .video) { granted in
            if granted {
                DispatchQueue.main.async {
                        let picket = UIImagePickerController()
                        picket.delegate = self
                        picket.sourceType = UIImagePickerController.SourceType.camera
                        picket.allowsEditing = false
                        self.present(picket, animated: true, completion: nil)
                }
            }else{
                DispatchQueue.main.async {
                    let alert = UINib(nibName: "M4PublicAlertView", bundle: nil).instantiate(withOwner: self).last as! M4PublicAlertView
                    alert.m4updateAlertUI(title: "Necesitas obtener permiso para la cámara. ¿Quieres ir a la configuración para activarla?", firstText: "Ir a la configuración", secondText: "Cancelar")
                    alert.M4AlertFirstBlock = {
                        UIApplication.shared.open(NSURL(string: UIApplication.openSettingsURLString)! as URL)
                    }
                    alert.M4AlertViewShow()
                }
            }
        }
    }
    
    private func M4ShowSystemAlbum() {
        PHPhotoLibrary.requestAuthorization { [self] status in
            if (status == .authorized) {
                DispatchQueue.main.async {
                    let albumVC = UIImagePickerController()
                    albumVC.view.backgroundColor = .white
                    albumVC.delegate = self
                    albumVC.allowsEditing = true
                    albumVC.sourceType = .photoLibrary
                    albumVC.modalPresentationStyle = .fullScreen
                    self.present(albumVC, animated: true, completion: nil)
                }
            }else{
                DispatchQueue.main.async {
                    let alert = UINib(nibName: "M4PublicAlertView", bundle: nil).instantiate(withOwner: self).last as! M4PublicAlertView
                    alert.m4updateAlertUI(title: "Necesito obtener permiso para el álbum de fotos. ¿Quieres ir a configuración para abrirlo?", firstText: "Ir a la configuración", secondText: "Cancelar")
                    alert.M4AlertFirstBlock = {
                        UIApplication.shared.open(NSURL(string: UIApplication.openSettingsURLString)! as URL)
                    }
                    alert.M4AlertViewShow()
                }
            }
        }
    }
    
    func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
        
        picker.dismiss(animated: true, completion: nil)
        let image = info[UIImagePickerController.InfoKey.originalImage] as! UIImage
        guard let imgData = M4Image.M4ImageCompress(image: image, maxSize: 5*1024*1024) else {return}
        let dataStr: String = imgData.base64EncodedString(options: [])
        M4UploadPhotoNet(imgBase64: dataStr)
    }
    
    func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
        picker.dismiss(animated: true) {
            self.dismiss(animated: true, completion: nil)
        }
    }
    
    
}




extension String {
    var containsEmoji: Bool {
        let controlCharacters = CharacterSet.controlCharacters
        let emojiCharacters = CharacterSet.symbols
        return self.rangeOfCharacter(from: controlCharacters.union(emojiCharacters)) != nil
    }
}
